package com.wstuo.common.config.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.config.basicConfig.service.ITimeZoneService;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.TimeUtils;

/**
 *  JSON数组与对象类型转换(用于日期类型转换)
 * @author Administrator
 *
 */
public class MyJsonValueProcessor implements JsonValueProcessor {
	@Autowired
	private ITimeZoneService timeZoneService;
	@Autowired
	private AppContext appctx;
	private final static Logger LOGGER = Logger.getLogger(MyJsonValueProcessor.class); 
	DateFormat format = new SimpleDateFormat(TimeUtils.DATETIME_PATTERN);
	public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
		String result = "";
		if(arg1 != null){
			if (arg1 instanceof Date) {
				Date date = (Date)arg1;
				TimeZone ctz = TimeZone.getDefault();
				try {
					try {
				    	String clientTimeZone = appctx.getAttributeByName("clientTimeZone");
				    	ctz =TimeZone.getTimeZone(clientTimeZone);
					} catch (Exception e) {
						// TODO: handle exception
						ctz = timeZoneService.getDefaultTimeZone("enduserTimeZone");
					}

				} catch (Exception e) {
					// TODO: handle exception
					LOGGER.debug("TimeZone Session Is Null Or External applications to access");
				}
		    	format.setTimeZone(ctz);
		    	result = format.format(date);	
			}else{
				result = arg1.toString();
			}
		}
		return result;
		
	}
	public Object processArrayValue(Object arg0, JsonConfig arg1) {
		// TODO Auto-generated method stub
		
		return null;
	}
}
